package com.birdboot.core;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler(Socket socket){
        this.socket=socket;
    }
    public void run(){
        try {
            //1.解析请求
            //1.1解析请求行
            String line=readLine();
            System.out.println("请求行："+line);
            String[] data=line.split("\\s");

            String method=data[0];
            String uri=data[1];
            String protocol=data[2];

            System.out.println("mehtod:"+method);
            System.out.println("uri:"+uri);
            System.out.println("protocol:"+protocol);
            //1.2解析消息头
            //消息头相关信息 key:消息头名字 value:消息头对应的值
            Map<String,String> headers=new HashMap<>();
            while (true){
                line=readLine();
                if(line.isEmpty()){
                    break;
                }
                System.out.println("消息头："+line);
                data=line.split(":\\s");
                headers.put(data[0],data[1]);
            }
            System.out.println("消息头："+headers);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //通过socket获取的输入流读取客户端发过来的一行字符串
    private String readLine() throws IOException {
        InputStream in=socket.getInputStream();
        int d;
        char pre='a',cur='a';//pre表示上次读取的字符，cur表示本次读取的字符
        StringBuilder builder=new StringBuilder();
        while ((d=in.read())!=-1){
            cur=(char) d;
            if(pre==13&&cur==10){
                break;
            }
            builder.append(cur);
            pre=cur;
        }
        return builder.toString().trim();
    }
}
